package marioarena;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Login
 */
@WebServlet("/login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Login() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Should not be accessed using HTTP GET, redirect to serverlist
		response.sendRedirect("ServerList");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("POST RECEIVED!");
		
		DbConnection dbConnection = new DbConnection();
		String loginResult = dbConnection.login(username, password);
		if (loginResult != null) // Login attempt has succeeded
		{
			System.out.println("Login succesful.");
			
			// Set the username session, meaning the user has logged in
			request.getSession().setAttribute("username", username);
			request.getSession().setAttribute("id", loginResult);
			response.sendRedirect(request.getContextPath() + "/ServerList");
		}
		else  // Login attempt has failed
		{
			System.out.println("Login failed.");
			
			// Notify to the serverlist that the login attempt has failed
			response.sendRedirect(request.getContextPath() + "/ServerList?login=failed");
		}
	}

}
